package jmsTopic;

import java.io.IOException;
import java.io.PrintWriter;

import javax.jms.JMSException;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class MessageConsumerAServlet
 */
public class MessagePublisherServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private TopicConnectionFactory conFactory;
	private TopicConnection connection;
	private TopicSession session;
	private TopicPublisher publisher;
	private Topic chatTopic;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public MessagePublisherServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession httpSession = request.getSession();
		
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<html><body>");
		out.println("<form method = \"GET\" name = \"cong\" action = \"Login.html\">");		
		out.println("<h2>Congratulations!You have successfully registered!</h2>");
		out.println("<h3>Try to</h3>");
		out.println("<input type=\"submit\" value=\"Login\" />");		
		out.println("</form></body></html>");
		
		
		OneMessage oneMsg = new OneMessage();
		oneMsg = (OneMessage) httpSession.getAttribute("message");
		
		try {
			InitialContext init = new InitialContext();
			conFactory = (TopicConnectionFactory) init.lookup("java:comp/env/jms/ConnectionFactory");
			chatTopic = (Topic) init.lookup("java:comp/env/jms/topic/MyTopic");
			
			connection = (TopicConnection) conFactory.createTopicConnection();
			session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);		
			publisher = session.createPublisher(chatTopic);

			connection.start();
			
			ObjectMessage objMsg = session.createObjectMessage();
			objMsg.setObject(oneMsg);
			publisher.send(objMsg);
	
			session.commit();
			
		} catch (NamingException e) {
			System.exit(1);
		} catch (JMSException e) {
			
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
